﻿namespace Authentication.Data.DataContextStorage
{
    using System.Collections;
    using System.Data.Entity;
    using System.Threading;
    public class ThreadDataContextStorageContainer : IDataContextStorageContainer
    {
        /// <summary>
        ///     The _lgevh data contexts.
        /// </summary>
        private static readonly Hashtable _applicationDataContexts = new Hashtable();

        /// <summary>
        ///     The get data context.
        /// </summary>
        /// <returns>
        ///     The <see cref="AuthenticationEntities" />.
        /// </returns>
        public DbContext GetDataContext()
        {
            DbContext applicationEntities = null;
            if (_applicationDataContexts.Contains(GetThreadName()))
            {
                applicationEntities = (AuthenticationEntities)_applicationDataContexts[GetThreadName()];
            }

            return applicationEntities;
        }

        /// <summary>
        /// The store.
        /// </summary>
        /// <param name="ApplicationEntities">
        /// The lgevh entities.
        /// </param>
        public void Store(DbContext ApplicationEntities)
        {
            if (_applicationDataContexts.Contains(GetThreadName()))
                _applicationDataContexts[GetThreadName()] = ApplicationEntities;
            else
                _applicationDataContexts.Add(GetThreadName(), ApplicationEntities);
        }

        /// <summary>
        ///     The get thread name.
        /// </summary>
        /// <returns>
        ///     The <see cref="string" />.
        /// </returns>
        private static string GetThreadName()
        {
            if (Thread.CurrentThread != null && !string.IsNullOrEmpty(Thread.CurrentThread.Name))
                return Thread.CurrentThread.Name;
            else
                return "AuthenticationDefaultThread";
        }
    }
}
